package com.yun.util;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class MailUtil {

    public static void main(String[] args) {
        List<String> receiverMailList = new ArrayList<>();
        receiverMailList.add("k19523719390@163.com");
        receiverMailList.add("kangning@icssla.com");
        StringBuilder content = new StringBuilder();
        content.append("报表任务名称：").append("aaa").append(";").append("当前时间：").append(date2String(new Date()));
        try {
            MailUtil.send("smtp.163.com", "k19523719390@163.com", "TXZMAKUAVZWHOYUP", "kn测试发件",
                    String.valueOf(content), "knknknknknkn", receiverMailList, false, "C:\\Users\\dell\\Desktop\\测试.docx");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param smtpHost           邮箱开启SMTP服务后会有展示 网易的SMTP地址为smtp.163.com
     * @param smtpUser           发件邮箱账号
     * @param smtpPassword       邮箱开启SMTP服务的授权码
     * @param subject            发件主题
     * @param content            发件内容
     * @param senderName         发件人名称
     * @param receiverMailList   接受邮件列表
     * @param ssl                发件端口是否使用SSl加密 默认smtp端口25 加密默认SMTP over SSL端口465
     * @param attachmentFilePath 发件携带附件 当前仅报表携带附件
     * @throws
     */
    public static void send(String smtpHost, String smtpUser, String smtpPassword, String subject, String content, String senderName, List<String> receiverMailList, boolean ssl, String attachmentFilePath) throws MessagingException, UnsupportedEncodingException {

        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        
        // debug 信息
//        props.put("mail.debug", "true");
        
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        if ( ssl ) {
            // 如果使用ssl
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.port", "465");
        } else {
        	props.put("mail.smtp.port", 25);   
        }
        // 发件人的账号
        props.put("mail.user", smtpUser);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", smtpPassword);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress( props.getProperty("mail.user") );
		try {
			form = new InternetAddress( props.getProperty("mail.user"), senderName );
		} catch (UnsupportedEncodingException e) {
			throw new MessagingException("设置发件人出错");
		}
        message.setFrom(form);

        // 设置邮件标题
        message.setSubject(subject);
        // 设置邮件的内容体
//        message.setContent(content, "text/html;charset=UTF-8");

        // 创建一个多部分消息 包含内容与附件
        Multipart multipart = new MimeMultipart();
        // 设置邮件内容
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(content, "text/html;charset=UTF-8");
        multipart.addBodyPart(textBodyPart);
//        设置邮件附件 当前只有报表使用
        if (attachmentFilePath != null && !attachmentFilePath.isEmpty()) {
            DataSource source = new FileDataSource(attachmentFilePath);
            BodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(source.getName(), "UTF-8", "B"));
            multipart.addBodyPart(attachmentBodyPart);
        }
        message.setContent(multipart);
        //创建收件人地址列表
        List<InternetAddress> listInternetAddress = new ArrayList<>();
        for ( String receiverMail : receiverMailList ) {
        	listInternetAddress.add( new InternetAddress( receiverMail ) );
        }
        InternetAddress[] sendTo = new InternetAddress[ listInternetAddress.size() ];
        listInternetAddress.toArray( sendTo );
        //标记为主要收件人
        message.setRecipients(MimeMessage.RecipientType.TO, sendTo);
        Transport.send(message);

	}


    /**
     * 时间转换成字符串 yyyy-MM-dd HH:mm:ss
     * @param date       时间
     * @return String
     */
    public static String date2String(Date date) {
        if (date == null) return "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    
//    public static void main(String[] args) {
//    	
//		String[] to = new String[1];
//		to[0] = "sdsss@xx.com";
//		
//    	try {
//			MailUtil.send("title测试"+System.currentTimeMillis(),"内容测试发送是否成功"+System.currentTimeMillis(), Arrays.asList(to), false);
//		} catch (MessagingException e) {
//			e.printStackTrace();
//		}
//    	
//    	System.out.println("test complate");
//	}
//    
}
